import { Injectable } from '@nestjs/common';
import { CreateFriendDto } from './dto/create-friend.dto';
import { UpdateFriendDto } from './dto/update-friend.dto';
import { PrismaService } from 'src/prisma.service';
import { User, UserMap } from '@prisma/client';
import { TRes } from 'src/common/base';

@Injectable()
export class FriendService {
  constructor(private prisma: PrismaService) { }

  async queryNotFriendsList(username: string, userId: string): Promise<TRes<User[]>>  {
    try {
      // 查询到的非朋友列表数据
      const list = []
      // 查询到所有的用户数据
      const registerData = await this.prisma.user.findMany({
        where: {
          username: {
            contains: username
          }
        }
      })
      const idsReq: TRes<string[]> = await this.existFriendIdList(userId)
      // 过滤掉已经成为好友的数据
      registerData.forEach(user => {
        if (!idsReq.data?.includes(user.userId)) {
          list.push(user)
        }
      })
      return {
        data: list,
      }
    } catch (error) {
      return {
        msg: error,
        data: null,
        sql: true // 执行sql失败
      }
    }
  }

  async existFriendIdList(userId: string): Promise<TRes<string[]>>  {
    try {

      const userMap = await this.prisma.userMap.findMany({
        where:  { userId: userId }
      })

      // 朋友的id列表
      const idsList = userMap.map((uMap: UserMap) => (uMap.friendId))
      idsList.push(userId)
      return {
        data: idsList,
      }
    } catch (error) {
      return {
        msg: error,
        data: null,
        sql: true // 执行sql失败
      }
    }
  }

  async queryFriendList(userId: string): Promise<TRes<User[]>>  {
    try {

      const userMap = await this.prisma.userMap.findMany({
        where:  { userId: userId }
      })

      // 朋友的id列表
      const friendsList = []

      for (const firend of userMap) {
        const f = await this.prisma.user.findUnique({ where: { userId: firend.friendId }})
        friendsList.push(f)
      }
      return {
        data: friendsList,
      }
    } catch (error) {
      return {
        msg: error,
        data: null,
        sql: true // 执行sql失败
      }
    }
  }

  update(id: number, updateFriendDto: UpdateFriendDto) {
    return `This action updates a #${id} friend`;
  }

  remove(id: number) {
    return `This action removes a #${id} friend`;
  }
}
